<?php

namespace AppBundle\Form;

use AppBundle\Entity\City;
use AppBundle\Entity\Country;
use AppBundle\Entity\Location;
use AppBundle\Entity\Region;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * @see Location
 * @author Vlad Riabchenko <vriabchenko@webnet.fr>
 */
class LocationType extends AbstractType
{
    /**
     * @var EntityManager
     */
    private $em;

    /**
     * Constructor.
     * @param EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * @inheritdoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'updateChoicesPreSetData'])
            ->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'updateChoicesPreSubmit'])
        ;
    }

    /**
     * @inheritdoc
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Location::class
        ]);
    }

    public function updateChoicesPreSubmit(FormEvent $event)
    {
        $requestData = $event->getData();
        $region = $this->em->getRepository(Region::class)->find($requestData['region'] ?? null);

        $this->addCountry($event->getForm());
        $this->addRegion($event->getForm(), $region);
        $this->addCity($event->getForm(), $region);
    }

    public function updateChoicesPreSetData(FormEvent $event)
    {
        $location = $event->getData();
        $city = $location instanceof Location ? $location->getCity() : null;
        $region = $city ? $city->getRegion() : null;
        $country = $region ? $region->getCountry() : null;

        $this->addCountry($event->getForm(), $country);
        $this->addRegion($event->getForm(), $region);
        $this->addCity($event->getForm(), $region);
    }

    /**
     * @param FormInterface $form
     * @param Country|null $country
     */
    private function addCountry(FormInterface $form, Country $country = null)
    {
        $form->add('country', EntityType::class, [
            'class' => Country::class,
            'choice_label' => 'name',
            'mapped' => false,
            'required' => true,
            'placeholder' => 'Select a country',
            'data' => $country
        ]);
    }

    /**
     * @param FormInterface $form
     * @param Region|null $region
     */
    private function addRegion(FormInterface $form, Region $region = null)
    {
        $form
            ->add('region', EntityType::class, [
                'class' => Region::class,
                'choice_label' => 'name',
                'mapped' => false,
                'required' => true,
                'placeholder' => 'Select a region',
                'data' => $region,
                'query_builder' => function (EntityRepository $repository) use ($region) {
                    return $repository
                        ->createQueryBuilder('r')
                        ->andWhere('r.country = :country')
                        ->setParameter('country', $region->getCountry());
                }
            ])
        ;
    }

    /**
     * @param FormInterface $form
     * @param Region|null $region
     */
    private function addCity(FormInterface $form, Region $region = null)
    {
        $form->add('city', EntityType::class, [
            'class' => City::class,
            'choice_label' => 'name',
            'placeholder' => 'Select a city',
            'query_builder' => function (EntityRepository $repository) use ($region) {
                return $repository
                    ->createQueryBuilder('c')
                    ->andWhere('c.region = :region')
                    ->setParameter('region', $region);
            }
        ]);
    }
}
